<?php
class ShopcountController extends AppController {

	public $name = 'shopcount';
	function beforeFilter() {
	    parent::beforeFilter(); 
		$this->C_auth->autoRedirect = false; //For override login
	    $this->C_auth->allowedActions = array('index','sell','stock');

	}

	public function stock() {	
        $this->_teamRights();	
	    $shopid = $this->my->id;
        $this->loadModel('supplier');	
		$resultsp = $this->supplier->find('all', array('conditions' => array('supplier.shop_id' => $shopid)));
		if(!empty($resultsp)) {
		    $stime = Request::get_args("stime");		
		    $etime = Request::get_args("etime");
			$title="";
            $str ="";			
            if($stime) {
	            $str .= " and g.jadd_time >= '$stime'";
				$title = $stime;
            }			
            if($etime) {
	            $str .= " and g.jadd_time  <= '$etime'";
				$title .= "  ~  ".$stime;
            }	
		
	        $supplierids = array();
            $ids="";			
		    foreach($resultsp as $v ) {
			    $supplierids[$v['supplier']['sup_user_id']] = $v['supplier']['sup_user_id'];
				$ids .= $v['supplier']['sup_user_id'].",";
			}
			$ids = substr($ids, 0,-1);
	        $this->loadModel('goodsstock');
	        $sql = "select g.supplier_user_id,sum(g.jnumber) as num,sum(g.jprice*g.jnumber) as countmoney from `".$this->goodsstock->tablePrefix."goods_stock` as g where g.shop_id=".$shopid." and g.supplier_user_id in(".$ids.") ".$str." group by g.supplier_user_id";
	        $result = $this->goodsstock->query($sql);			
	        Loader::import('lib.GoogChart');
            $chart1 = new GoogChart();
            $chart2 = new GoogChart();			
            // Set graph data			
			$numdata = array();
			$moneydata = array();
            $supdata = array();	
		
			foreach($result as $v) {
			    $numdata["ID:".$v['g']['supplier_user_id']] = $v[0]['num'];
			    $moneydata["ID:".$v['g']['supplier_user_id']] = $v[0]['countmoney'];
              	$supdata[$v['g']['supplier_user_id']] =$v[0];			
			}			
            // Set graph colors
            $color = array(
			'#99C754',
			'#54C7C5',
			'#999999',
		    );
            // # Chart 1 # 
            $chart1->setChartAttrs( array(
	        'type' => 'pie',
	        'title' => $title,
	        'data' => $numdata,
	        'size' => array( 400, 300 ),
	        'color' => $color
	        ));
            $this->set('chart1',$chart1);
            $chart2->setChartAttrs( array(
	        'type' => 'pie',
	        'title' => $title,
	        'data' => $moneydata,
	        'size' => array( 400, 300 ),
	        'color' => $color
	        ));			
            $this->set('chart2',$chart2);				
            $this->set('supdata',$supdata);
            $this->set('resultsp',$resultsp);
            $this->set('stime',$stime);
            $this->set('etime',$etime);			
		}else {
		    $this->flash("你还没有创建供货商账户，请先创建供货商！", Router::url('supplier/index/'));
		}
		
	}
	
	public function sell() {	
        $this->_teamRights();	
        if(isset($_GET['state'])){ $state=intval($_GET['state']); } else {$state=''; }
		$salesman = Request::get_args("salesman");
		$cusname = Request::get_args("cusname");
		$stime = Request::get_args("stime");		
		$etime = Request::get_args("etime");        
		if(empty($stime) || empty($etime)){
            $stime = date('Y-m-d', mktime(0,0,0,date('m')-3,1,date('Y')));
		    $etime = date('Y-m-d');
		}
		$alltime = $this->timeBetween(strtotime($stime),strtotime($etime));
		$allmonth = array();
        foreach($alltime as $v) {
		    $t = substr($v['time_start'], 0,-3);
		    $allmonth[$t] = $t;
		}
		if(count($allmonth)>4) {
		    $this->flash("最多显示4个月的数据，请从新选择日期", Router::url('shopcount/sell/'));
		} else {
		$title = reset($allmonth)."  ~  ".end($allmonth);
		$user_id = $this->my->id;		
	    $result = array();
		$str="";
		if(!empty($state)){
			switch ($state){
				case 1:
					$str.=" and oi.order_status=1 ";break;
				case 2:
					$str.=" and oi.order_status=2 ";break;
				case 3:
					$str.=" and oi.pay_status=0 ";break;
				case 4:
					$str.=" and oi.pay_status=1 ";break;
				case 5:
					$str.=" and oi.transport_status=0 ";break;
				case 6:
					$str.=" and oi.transport_status=1 ";break;
				case 7:
					$str.=" and oi.order_status=3 ";break;
				case 8:
					$str.=" and oi.transport_status=0 and oi.pay_status=1 ";break;
				case 9:
					$str.=" and oi.order_status=3 and oi.seller_reply='0' ";break;
			}
		}
        $this->loadModel('orderinfo');
		if(!empty($salesman) || !empty($cusname)) {
		    if(!empty($salesman)) {
		        $str.=" and sc.salesman_user_name= '$salesman' ";
		    }
		    if(!empty($cusname)) {
		        $str.=" and sc.user_name='$cusname' ";
		    }		
	        $sql = "select count(*) as num,sum(og.goods_price*og.order_num) as countmoney,sum(if(oi.pay_status=0,og.goods_price*og.order_num,0)) as nopay,sum(if(oi.pay_status=1,og.goods_price*og.order_num,0)) as pay
			from `".$this->orderinfo->tablePrefix."order_goods` AS og  join  `".$this->orderinfo->tablePrefix."order_info` AS oi on og.order_id=oi.id join `".$this->orderinfo->tablePrefix."goods` as g on og.goods_id=g.id join `".$this->orderinfo->tablePrefix."shop_info` as s on og.shop_id=s.id join `".$this->orderinfo->tablePrefix."shop_customer` as sc on ( og.shop_id=sc.shop_id and oi.user_id=sc.user_id ) 
			where  og.shop_id=" .$user_id." " .$str." ";
		
        } else {
	        $sql = "select count(*) as num,sum(og.goods_price*og.order_num) as countmoney,sum(if(oi.pay_status=0,og.goods_price*og.order_num,0)) as nopay,sum(if(oi.pay_status=1,og.goods_price*og.order_num,0)) as pay
			from `".$this->orderinfo->tablePrefix."order_goods` AS og  join  `".$this->orderinfo->tablePrefix."order_info` AS oi on og.order_id=oi.id   
			where  og.shop_id=" .$user_id." ".$str." ";
		}
        $result = array();		
        foreach($alltime as $v) {
		    $t = substr($v['time_start'], 0,-3);
			$sql1 = $sql . " and og.add_time >= '".$v['time_start']."' and og.add_time  <= '".$v['time_end']."'";
		    $result[$t] = $this->orderinfo->query( $sql1 );		
		}	
	    $name =array(
		'Order Amount'=>'countmoney',
		'The Payment'=>'pay',
		'Not payment'=>'nopay',
		'Order Frequency'=>'num'
		);
		$dataMultiple = array();
		foreach($name as $k => $v) {
		    foreach($result as $key => $val) {
			    if(empty($val[0][0][$v]))$val[0][0][$v]=0;
			    $dataMultiple[$k][$key] = $val[0][0][$v];
			}
		}
		$max =0;
		foreach($dataMultiple as $k => $v) {
		    foreach($v as $k1 => $v1) {
			    if($v1>$max)$max=$v1;
			}
		}
		$max = intval($max);
		$bmax = intval($this->str_insert($max.'',2,'.'));
		if($bmax) {
		    $bainum = intval($max/$bmax);
		}else {
		    $bainum = 0;
		}
		
		$bainum = str_replace(array('1','2','3','4','5','6','7','8','9'),'0',$bainum.'');
		$bainum = intval('1'.substr($bainum, 0,-1));
		$dataMultiple = array();
		foreach($name as $k => $v) {
		    foreach($result as $key => $val) {
			    if(empty($val[0][0][$v]))$val[0][0][$v]=0;
			    $dataMultiple[$k][$key] = $val[0][0][$v]/$bainum;
			}
		}

	        Loader::import('lib.GoogChart');
            $chart1 = new GoogChart();
            $color = array(
			'#99C754',
			'#54C7C5',
			'#999999',
			'#000000',			
		    );			

        // # Chart 2 # 
        $chart1->setChartAttrs( array(
	        'type' => 'bar-vertical',
	        'title' => $title,
	        'data' => $dataMultiple,
	        'size' => array( 650, 300 ),
	        'color' => $color,
	        'labelsXY' => true,
	    ));			
        $this->set('state',$state);
        $this->set('salesman',$salesman);
        $this->set('cusname',$cusname);		
		
        $this->set('stime',$stime);
        $this->set('etime',$etime);
		
        $this->set('chart1',$chart1);
        $this->set('result',$result);
        $this->set('bainum',$bainum);	
        }		
	}
	
function str_insert($str, $i, $substr)
{
if(empty($str))return 0;
$startstr = $laststr ='';
for($j=0; $j<$i; $j++){
$startstr .= $str[$j];
}
for ($j=$i; $j<strlen($str); $j++){
$laststr .= $str[$j];
}
$str = ($startstr . $substr . $laststr);
return $str;
} 

	public function timeBetween($start, $end){
        $d_s = strtotime(date('Y-m', $start));
        $d_e = strtotime(date('Y-m', $end));

  $num = 1; 
  $dates = array();
 
     while ($start<=$end){
   if($d_s == $d_e){
    $dates[] = array(
     'time_start' => date('Y-m-d',$start),
     'time_end' => date('Y-m-d',$end),
    );
    break;
   }else{
    if($num == 1){
     $dates[] = array(
      'time_start' => date('Y-m-d',$start),
      'time_end' => date('Y-m-t',$start),
     );
    }else{
     $dates[] = array(
      'time_start' => date('Y-m' . '-01',$start),
      'time_end' => date('Y-m-t',$start),
     ); 
    }
    $start = strtotime('+1 month',$start); 
   }
   $num ++;
     }
  $pop_ele = array_pop($dates);
  $pop_ele['time_end'] = date('Y-m-d',$end);
 
  array_push($dates, $pop_ele);
  return $dates;
 }	
	
	
	
	
	
	
	
	
	
	
	
	
	//店铺收到的订单
	public function index() {	
        $this->_teamRights();	
		if(!isset(Request::$query['page']))Request::$query['page']=1;
        $page = intval(Request::$query['page']);	
        if(isset($_GET['state'])){ $state=intval($_GET['state']); } else {$state=''; }
		$salesman = Request::get_args("salesman");
		$cusname = Request::get_args("cusname");
		$stime = Request::get_args("stime");		
		$etime = Request::get_args("etime");		
		$user_id = $this->my->id;
        $this->loadModel('shopinfo');		
        $SHOP = $this->shopinfo->find('first', array('conditions' => array('shopinfo.user_id' => $user_id)));
		if(!$SHOP) { exit("店铺不存在");}//没有此商铺
		$SHOP = $SHOP['shopinfo'];		
	    if($SHOP['open_flg']) {
		    exit("此商铺已关闭");
	    }//关闭		
        if($this->my->locked==1){
	        $this->C_session->destroy();
	        exit("您已经被锁定了");//非法操作
        }
	    $result = array();
		$str="";
		if(!empty($state)){
			switch ($state){
				case 1:
					$str.=" and oi.order_status=1 ";break;
				case 2:
					$str.=" and oi.order_status=2 ";break;
				case 3:
					$str.=" and oi.pay_status=0 ";break;
				case 4:
					$str.=" and oi.pay_status=1 ";break;
				case 5:
					$str.=" and oi.transport_status=0 ";break;
				case 6:
					$str.=" and oi.transport_status=1 ";break;
				case 7:
					$str.=" and oi.order_status=3 ";break;
				case 8:
					$str.=" and oi.transport_status=0 and oi.pay_status=1 ";break;
				case 9:
					$str.=" and oi.order_status=3 and oi.seller_reply='0' ";break;
			}
		}
		if(!empty($salesman)) {
		    $str.=" and sc.salesman_user_name= '$salesman' ";
		}
		if(!empty($cusname)) {
		    $str.=" and sc.user_name='$cusname' ";
		}	
        if($stime) {
	        $str .= " and og.add_time >= '$stime'";
        }
        if($etime) {
	        $str .= " and og.add_time  <= '$etime'";
        }		
		
        $this->loadModel('orderinfo');	

/*         $tb=array('table' => "`".$this->orderinfo->tablePrefix."order_goods` AS og ,`".$this->orderinfo->tablePrefix."order_info` AS oi ,`".$this->orderinfo->tablePrefix."goods` as g, `".$this->orderinfo->tablePrefix."shop_info` as s, `".$this->orderinfo->tablePrefix."shop_customer` as sc",
     		'fields' =>" og.order_id,og.goods_id,og.goods_price,og.order_num,og.good_tran,oi.payid,oi.order_status,oi.protect_status,oi.pay_status,oi.transport_status,og.add_time,g.goods_thumb,og.id,g.lock_flg,s.user_id,s.shop_name,g.goods_name,s.id as shop_id,sc.salesman_user_name,sc.user_name ",
			'conditions' => " og.order_id=oi.id and og.goods_id=g.id and og.shop_id=s.id and oi.user_id=sc.user_id and og.shop_id=" .$user_id." " .$str,
			'order' => ' og.goods_id desc ',
			'limit' => '13', 'url' => Router::url('shopcount/index/?state='.$state.'&salesman='.$salesman.'&=cusname'.$cusname.'&stime='.$stime.'&etime='.$etime),
			'page' => $page,'plist' => 6,
			'startPage' => true,'DbConfig' => null
			) ; 	 */	
		
		if(!empty($salesman) || !empty($cusname)) {
            $tb=array('table' => "`".$this->orderinfo->tablePrefix."order_goods` AS og  join  `".$this->orderinfo->tablePrefix."order_info` AS oi on og.order_id=oi.id join `".$this->orderinfo->tablePrefix."goods` as g on og.goods_id=g.id join `".$this->orderinfo->tablePrefix."shop_info` as s on og.shop_id=s.id join `".$this->orderinfo->tablePrefix."shop_customer` as sc on ( og.shop_id=sc.shop_id and oi.user_id=sc.user_id ) ",
     		'fields' =>" og.order_id,og.goods_id,og.goods_price,og.order_num,og.good_tran,oi.payid,oi.order_status,oi.protect_status,oi.pay_status,oi.transport_status,og.add_time,g.goods_thumb,og.id,g.lock_flg,s.user_id,s.shop_name,g.goods_name,s.id as shop_id,sc.salesman_user_name,sc.user_name ",
			'conditions' => " og.shop_id=" .$user_id." " .$str,
			'order' => ' og.order_id desc ',
			'limit' => '13', 'url' => Router::url('shopcount/index/?state='.$state.'&salesman='.$salesman.'&cusname='.$cusname.'&stime='.$stime.'&etime='.$etime),
			'page' => $page,'plist' => 6,
			'startPage' => true,'DbConfig' => null
			) ;  
	        $result =  $this->fetch_page($tb);			
        } else {
            $tb=array('table' => "`".$this->orderinfo->tablePrefix."order_goods` AS og  join  `".$this->orderinfo->tablePrefix."order_info` AS oi on og.order_id=oi.id join `".$this->orderinfo->tablePrefix."goods` as g on og.goods_id=g.id join `".$this->orderinfo->tablePrefix."shop_info` as s on og.shop_id=s.id ",
     		'fields' =>" og.order_id,og.goods_id,og.goods_price,og.order_num,og.good_tran,oi.payid,oi.order_status,oi.protect_status,oi.pay_status,oi.transport_status,oi.user_id as pay_user_id,og.add_time,g.goods_thumb,og.id,g.lock_flg,s.user_id,s.shop_name,g.goods_name,s.id as shop_id ",
			'conditions' => " og.shop_id=" .$user_id." " .$str,
			'order' => ' og.order_id desc ',
			'limit' => '13', 'url' => Router::url('shopcount/index/?state='.$state.'&salesman='.$salesman.'&cusname='.$cusname.'&stime='.$stime.'&etime='.$etime),
			'page' => $page,'plist' => 6,
			'startPage' => true,'DbConfig' => null
			) ;
	        $result =  $this->fetch_page($tb);
			if(isset($result['data'])){
                $payuser = array();			
                foreach($result['data'] as $val) {
                    if(!isset($payuser[$val['pay_user_id']])){
					    $payuser[$val['pay_user_id']] = $val['pay_user_id'];
					}
                }
                $this->loadModel('shopcustomer');
                $temp = $this->shopcustomer->find('all', array('conditions' => array('shopcustomer.shop_id' => $this->my->id,'shopcustomer.user_id' => $payuser)));	
				foreach($temp as $val) { 				
				    foreach($result['data'] as $key1 =>$val1) {
                        if($val['shopcustomer']['user_id']==$val1['pay_user_id']){
                            $result['data'][$key1]['salesman_user_name'] =$val['shopcustomer']['salesman_user_name'];
                            $result['data'][$key1]['user_name'] = $val['shopcustomer']['user_name'];					
					    }
					}
                }				
            }		
		}


		$this->loadModel('payment');
		$array = $this->payment->find('all', array('conditions' => array('payment.enabled'=>1)));
	    $payment_info = array();
	    foreach($array as $value) {
		    $payment_info[$value['payment']['id']] = $value['payment'];
	    }	
        $this->set('state',$state);
        $this->set('salesman',$salesman);
        $this->set('cusname',$cusname);		
		
        $this->set('stime',$stime);
        $this->set('etime',$etime);
		
        $this->set('result',$result);
		$this->set('payment_info',$payment_info);
	}		
	
	
	
}


?>